#include <sha1.h>
#include <Time.h>

#define LED_PIN       13
#define TIME_MSG_LEN  0x0B   
#define TIME_HEADER   0x54    // echo T$(($(date +%s))) > /dev/ttyACM0
#define TIME_REQUEST  0x07     
#define ANNOUNCEMENT  0x16    // SYN  |
#define ACKNOWLEDGE   0x06    // ACK  |  HEX
#define KEY_FAILURE   0x15    // NAK  |
#define KEY_SUCCESS   0x2A    // *    |

boolean Synced   =    false;

union KeyforSending{
  uint32_t key;
  char     Byte[32];
}Send;

uint8_t Key[]={
 0x66, 0x7C, 0x18, 0x40, 0xA8,      // Randomly Generated Key
 0x2F, 0x68, 0x61, 0xDA, 0xB1       // 667C1840A82F6861DAB1  HEX 
};                                  // mz6bqqfif5ugdwvr      BASE32

uint8_t time[]={
   0x00,0x00,0x00,0x00,
   0x00,0x00,0x00,0x00
};

void setup() {
  delay(50)
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
    if(timeStatus() == timeNotSet) {
        if(Serial.available() ) {
        TimeSync();
        }
        Serial.println("waiting for time sync");
        BlinkLED();
    } else {
      if(Serial1.available()){
        char c = Serial1.read();
        switch(c){
         case ACKNOWLEDGE :
           Synced = true;
           ProcessKey();
           for(int i = 0; i < 32; i++){
             Serial1.write(Send.Byte[i]);
           }
           break;
         case KEY_FAILURE :
           delay(1000);
           ProcessKey();
           for(int i = 0; i < 32; i++){
             Serial1.write(Send.Byte[i]);
           }
           break;
         case KEY_SUCCESS :
           BlinkLED();
           break;
       }
     }
     Serial1.write(ANNOUNCEMENT);
   }
} 



